<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
          <el-option v-for="dict in meetingroom_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="价格" prop="hourlyRate">
        <el-input v-model="queryParams.hourlyRate" placeholder="请输入每小时租赁价格" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in meetingroom_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="面积" prop="area">
        <el-input v-model="queryParams.area" placeholder="请输入面积" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="多媒体" prop="isSupport">
        <el-select v-model="queryParams.isSupport" placeholder="请选择多媒体系统" clearable>
          <el-option v-for="dict in meetingroom_support" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="开始" prop="startTime">
        <el-date-picker clearable v-model="queryParams.startTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm:ss" placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束" prop="endTime">
        <el-date-picker clearable v-model="queryParams.endTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm:ss" placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['system:meetingroom:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:meetingroom:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:meetingroom:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['system:meetingroom:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="meetingroomList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="roomId" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="meetingroom_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="容纳人数" align="center" prop="capacity" />
      <el-table-column label="每小时租赁价格" align="center" prop="hourlyRate" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="meetingroom_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="面积" align="center" prop="area" />
      <el-table-column label="教室设备清单" align="center" prop="equipment" />
      <el-table-column label="多媒体系统" align="center" prop="isSupport">
        <template #default="scope">
          <dict-tag :options="meetingroom_support" :value="scope.row.isSupport" />
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="description" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:meetingroom:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:meetingroom:remove']">删除</el-button>
          <el-button link type="primary" icon="Calendar" @click="handleReserve(scope.row)"
            v-hasPermi="['system:meetingroom:reserve']">预订</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改会议室信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="meetingroomRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option v-for="dict in meetingroom_type" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="hourlyRate">
          <el-input v-model="form.hourlyRate" placeholder="请输入每小时租赁价格" />
        </el-form-item>

        <el-form-item label="容纳人数" prop="capacity">
          <el-input v-model="form.capacity" placeholder="请输入容纳人数" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option v-for="dict in meetingroom_status" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="面积" prop="area">
          <el-input v-model="form.area" placeholder="请输入面积" />
        </el-form-item>
        <el-form-item label="设备清单" prop="equipment">
          <el-input v-model="form.equipment" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="多媒体" prop="isSupport">
          <el-select v-model="form.isSupport" placeholder="请选择多媒体系统">
            <el-option v-for="dict in meetingroom_support" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!-- 预订会议室表单 -->
  <el-dialog title="预定会议室" v-model="reserveDialog" width="500px" append-to-body>
    <el-form ref="reserveFormRef" :model="reserveForm" :rules="reserveRules" label-width="80px">
      <el-form-item label="会议室名称">
        <el-input v-model="currentRoom.name" disabled />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker v-model="reserveForm.startTime" type="datetime" placeholder="请选择开始时间"
          value-format="YYYY-MM-DD HH:mm:ss" :disabled-date="disabledDate" :shortcuts="shortcuts" />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker v-model="reserveForm.endTime" type="datetime" placeholder="请选择结束时间"
          value-format="YYYY-MM-DD HH:mm:ss" :disabled-date="disabledDate" :shortcuts="shortcuts"
          :disabled="!reserveForm.startTime" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="reserveDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitReserve">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="Meetingroom">
import { listMeetingroom, getMeetingroom, delMeetingroom, addMeetingroom, updateMeetingroom, reserveMeetingroom } from "@/api/system/meetingroom"

const { proxy } = getCurrentInstance()
const { meetingroom_support, meetingroom_status, meetingroom_type } = proxy.useDict('meetingroom_support', 'meetingroom_status', 'meetingroom_type')

const meetingroomList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const reserveDialog = ref(false)
const currentRoom = ref({})
const reserveForm = reactive({
  startTime: '',
  endTime: ''
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    type: null,
    capacity: null,
    hourlyRate: null,
    status: null,
    area: null,
    equipment: null,
    isSupport: null,
    description: null,
  },
  rules: {
    name: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "类型不能为空", trigger: "change" }
    ],
    capacity: [
      { required: true, message: "容纳人数不能为空", trigger: "blur" }
    ],
    hourlyRate: [
      { required: true, message: "每小时租赁价格不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    area: [
      { required: true, message: "面积不能为空", trigger: "blur" }
    ],
    equipment: [
      { required: true, message: "教室设备清单不能为空", trigger: "blur" }
    ],
    isSupport: [
      { required: true, message: "多媒体系统不能为空", trigger: "change" }
    ],
    createBy: [
      { required: true, message: "创建人不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
    capacity: [
      { required: true, message: "容纳人数不能为空", trigger: "blur" }
    ],
  }
})

const reserveRules = reactive({
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && reserveForm.startTime && new Date(value) <= new Date(reserveForm.startTime)) {
          callback(new Error('结束时间必须晚于开始时间'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
})

// 时间选择快捷选项
const shortcuts = [
  {
    text: '今天',
    value: new Date()
  },
  {
    text: '明天',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() + 3600 * 1000 * 24)
      return date
    }
  },
  {
    text: '一周后',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
      return date
    }
  }
]

// 禁用今天之前的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7 // 86400000 = 24 * 60 * 60 * 1000
}


const { queryParams, form, rules } = toRefs(data)

/** 查询会议室信息列表 */
function getList() {
  loading.value = true
  listMeetingroom(queryParams.value).then(response => {
    meetingroomList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    roomId: null,
    name: null,
    type: null,
    capacity: null,
    hourlyRate: null,
    status: null,
    area: null,
    equipment: null,
    isSupport: null,
    description: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("meetingroomRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.roomId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加会议室信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _roomId = row.roomId || ids.value
  getMeetingroom(_roomId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改会议室信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["meetingroomRef"].validate(valid => {
    if (valid) {
      if (form.value.roomId != null) {
        updateMeetingroom(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addMeetingroom(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _roomIds = row.roomId || ids.value
  proxy.$modal.confirm('是否确认删除会议室信息编号为"' + _roomIds + '"的数据项？').then(function () {
    return delMeetingroom(_roomIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/meetingroom/export', {
    ...queryParams.value
  }, `meetingroom_${new Date().getTime()}.xlsx`)
}

// 预订按钮操作
function handleReserve(row) {
  // 检查会议室状态是否为预定状态
  if (row.status !== 1) {
    proxy.$modal.msgError("当前会议室不允许预订")
    return
  }
  currentRoom.value = row
  reserveForm.startTime = ''
  reserveForm.endTime = ''
  reserveDialog.value = true
}

// 提交预定
function submitReserve() {
  proxy.$refs['reserveFormRef'].validate(valid => {
    if (valid) {
      const reserveData = {
        roomId: currentRoom.value.roomId,
        startTime: reserveForm.startTime,
        endTime: reserveForm.endTime
      }

      reserveMeetingroom(reserveData).then(response => {
        proxy.$modal.msgSuccess("预订订单创建成功，请及时支付")
        reserveDialog.value = false
      }).catch(error => {
      })
    }
  })
}


getList()
</script>
